'use strict';

const net = require('net');

const Terminal = require('./terminal');

module.exports = class SocketServer {

  constructor(options, app) {
    this.options = options;
    this.app = app;
    const server = net.createServer(socket => {
      this.onConnect(socket);
    });

    this.server = server;
    this.terminals = new Map();

    app.messenger.on('iot_action', data => {
      this.app.logger.info('iot action', data);
      this.send(data);
    });
  }

  onConnect(socket) {
    const terminal = new Terminal(socket, this.app);

    terminal.on('ready', id => {
      this.terminals.set(id, terminal);
    });

    terminal.on('leave', id => {
      this.terminals.delete(id);
    });

    terminal.on('data', pack => {
      this.app.messenger.sendToApp('iot_action', {
        id: terminal.id,
        data: pack,
        online: true,
      });
    });
  }

  start() {
    this.server.listen(this.options.port);
    this.app.logger.info(`socket server start at :${this.options.port}`);
  }

  send({ id, data }) {
    console.log(id, this.terminals);
    if (this.terminals.has(id)) {
      const terminal = this.terminals.get(id);

      terminal.send(data);
    } else {
      this.app.messenger.sendToApp('iot_action', {
        id,
        data,
        online: false,
      });
    }
  }
};
